package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 安全认证
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
    //dubbo 的RPC远程调用
    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.findByUsername(username);
        //判断user对象是否存在
        if(user == null){
            return null;
        }
        //创建list集合对象
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        //查询角色信息
        Set<Role> roles = user.getRoles();
        //遍历roles集合取出角色信息
        for (Role role : roles) {
            String keyword = role.getKeyword();
            list.add(new SimpleGrantedAuthority(keyword));
            //取出权限集合
            Set<Permission> permissions = role.getPermissions();
            //循环取出
            for (Permission permission : permissions) {
                String keyword1 = permission.getKeyword();
                list.add(new SimpleGrantedAuthority(keyword1));

            }
        }
        //返回springSecurityUser对象做对比
        org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return securityUser;
    }
}
